package api.betfairAPI;

import api.APICallRateMonitor;
import com.google.common.base.Optional;
import org.apache.log4j.Logger;
import utils.Display;

import java.util.concurrent.ScheduledExecutorService;

/**
 * User: Darren
 * Date: 7/04/13
 * Time: 2:29 PM
 */
public class BetfairAPICallRate {
    private static Logger logger = Logger.getLogger(BetfairAPICallRate.class);
    private Optional<APICallRateMonitor> monitorOptional = Optional.absent();
    private final int PRODUCT_ID;
    private Optional<Display> displayOptional = Optional.absent();

    public BetfairAPICallRate(int productId) {
        this.PRODUCT_ID = productId;
    }

    public BetfairAPICallRate(int productId, ScheduledExecutorService scheduler, Display display) {
        this.PRODUCT_ID = productId;
        monitorOptional = Optional.of(new APICallRateMonitor(scheduler));
        this.displayOptional = Optional.of(display);
    }

    public int getProductId() {
        return PRODUCT_ID;
    }

    public boolean isMonitored() {
        return monitorOptional.isPresent() && displayOptional.isPresent();
    }

    public boolean callExceedsLimit(BetfairAPICallTypes apiCallType) {
        if (!isMonitored()) {
            return false;
        }
        if (monitorOptional.get().callExceedsLimit(apiCallType)) {
            logger.error("The Betfair API's free access limit will be exceeded with another called to: "
                    + apiCallType.getName());
            displayOptional.get().displayTotalAndCallPerSecond(monitorOptional.get(), apiCallType);
            return true;
        }
        return false;
    }
}
